package com.ruoyi.binance.dingding;

import cn.hutool.core.map.MapUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.ruoyi.binance.domain.BinanceTransactionOrder;
import com.ruoyi.common.utils.DateUtils;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;


public class DingDingSendMsgUtils {

    /**
     * 提示@所有人
     *
     * @param msg 通知消息
     */
    public static void sendMessageAtAll(String msg) {
        Map<String, Object> atMap = MapUtil.newHashMap();
        atMap.put("isAtAll", true);
        String reqString = getString(msg, atMap);
        HttpRequest.post(getSignUrl()).body(reqString).timeout(Config.timeout).execute().body();
    }

    /**
     * 提示@具体选择的某个人
     *
     * @param msg        通知消息
     * @param mobileList 通知人的电话号码
     */
    public static void sendMessageAtChosePerson(String msg, List<String> mobileList) {
        Map<String, Object> atMap = MapUtil.newHashMap();
        atMap.put("isAtAll", false);
        atMap.put("atMobiles", mobileList);
        String reqString = getString(msg, atMap);
        HttpRequest.post(getSignUrl()).body(reqString).timeout(Config.timeout).execute().body();
    }

    private static String getString(String msg, Map<String, Object> atMap) {
        Map<String, String> contentMap = MapUtil.newHashMap();
        contentMap.put("content", msg);
        Map<String, Object> reqMap = MapUtil.newHashMap();
        reqMap.put("msgtype", "text");
        reqMap.put("text", contentMap);
        reqMap.put("at", atMap);
        return JSONUtil.toJsonStr(reqMap);
    }

    private static String getSignUrl() {
        try {
            //群机器人复制到的秘钥secret
            String secret = Config.SIGN_KEY;
            //获取系统时间戳
            Long timestamp = System.currentTimeMillis();
            //拼接
            String stringToSign = timestamp + "\n" + secret;
            //使用HmacSHA256算法计算签名
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256"));
            byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
            //进行Base64 encode 得到最后的sign，可以拼接进url里
            String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");
            //钉钉机器人地址（配置机器人的webhook），为了让每次请求不同，避免钉钉拦截，加上时间戳
            return Config.webhook + "&timestamp=" + timestamp + "&sign=" + sign;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Config.webhook;
    }


    /**
     * 均价提醒模版
     */
    public static String getAveragePriceTemplate(String signal, String code,
                                                 String averagePrice, String price,
                                                 String setConfig, String time, String averageType) {
        return "操作信号：" + signal + "\n" +
                "代码：" + code + "\n" +
                averageType + "均价：" + averagePrice + "\n" +
                "触发价格：" + price + "\n" +
                "触发配置：" + setConfig + "%\n" +
                "触发时间：" + time + "\n";
    }

    public static String getTranMessageTemplate(BinanceTransactionOrder order) {
        String s = order.getSide().equals("BUY") ? "买入" : "卖出";
        return "操作信号：" + s + "\n" +
                "代码：" + order.getCode() + "\n" +
                "单价：" + order.getPrice() + "\n" +
                "成交数量：" + order.getExecutedQty() + "\n" +
                "订单状态：成功" + "\n" +
                "交易时间：" + DateUtils.getFormatTime(order.getTransactTime()) + "\n";
    }
}
